package concurrecy;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class TerminatedIOTask implements Runnable {
    private InputStream stream;
    public TerminatedIOTask(InputStream stream) {
        this.stream = stream;
    }

    @Override
    public void run() {
        System.out.println("ready read from " + stream.getClass().getSimpleName());
        try {
            stream.read();
        } catch (IOException e) {
            System.out.println("read error, " + e.getMessage());
        }
        System.out.println("Exit from run " + stream.getClass().getSimpleName());
    }
}

public class TerminateIOTaskDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new TerminatedIOTask(System.in));
        ServerSocket serverSocket = new ServerSocket(8080);
        InputStream socketStream = new Socket("localhost", 8080).getInputStream();
        service.execute(new TerminatedIOTask(socketStream));

        TimeUnit.SECONDS.sleep(2);
        System.out.println("shutdown now");
        List<Runnable> runnables = service.shutdownNow();
        System.out.println(runnables.size());
        for (Runnable runnable : runnables) {
            System.out.println(runnable);
        }
        TimeUnit.SECONDS.sleep(2);

        System.out.println("socket close");
        serverSocket.close();
        TimeUnit.SECONDS.sleep(2);
        System.out.println("system.in close");
        System.in.close();
    }
}
